// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.core.export;

import static org.dengues.core.export.EtlProcessScriptsManager.PATH_SEPARATOR;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.dengues.core.ExceptionOperation;
import org.dengues.core.i18n.Messages;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-4-10 qiang.zhang $
 * 
 */
public class FileSystemExportScriptOperation implements IRunnableWithProgress {

    private final EtlProcessScriptsManager manager;

    private List<ExportFileResource> zExportResList;

    private FileSystemExporterFullPath exporter;

    private IProgressMonitor monitor;

    private final String destinationPath;

    /**
     * Qiang.Zhang.Adolf@gmail.com FileSystemExportScriptOperation constructor comment.
     * 
     * @param exportResList
     */
    public FileSystemExportScriptOperation(List<ExportFileResource> exportResList, String destinationPath) {
        manager = new EtlProcessScriptsManager();
        this.zExportResList = exportResList;
        Path path = new Path(destinationPath);
        this.destinationPath = path.toOSString();
        File file = new File(this.destinationPath);
        if (file.exists()) {
            file.deleteOnExit();
        }
        file.mkdirs();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
     */
    public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
        this.monitor = monitor;
        try {
            // ie.- a single resource for recursive export was specified
            int totalWork = IProgressMonitor.UNKNOWN;

            monitor.beginTask(Messages.getString("FileSystemExportScriptOperation.export"), totalWork); //$NON-NLS-1$
            zExportResList = manager.getExportResources(zExportResList, monitor);

            if (zExportResList != null) {
                totalWork = countSelectedResources();
            }

            exporter = new FileSystemExporterFullPath();
            exportSpecifiedResources();
        } catch (Exception e) {
            ExceptionOperation.operate(e);
        } finally {
            monitor.done();
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "exportSpecifiedResources".
     * 
     * @throws InterruptedException
     */
    private void exportSpecifiedResources() throws InterruptedException {
        for (ExportFileResource fileResource : zExportResList) {

            Set<String> paths = fileResource.getRelativePathList();
            for (Iterator iter = paths.iterator(); iter.hasNext();) {
                String relativePath = (String) iter.next();
                Set<URL> resource = fileResource.getResourcesByRelativePath(relativePath);
                for (URL url : resource) {
                    String currentResource = url.getPath();
                    exportFile(relativePath, currentResource);
                }
            }
        }

    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "exportFile".
     * 
     * @param rootName
     * @param relativePath
     * @param currentResource
     * @throws InterruptedException
     */
    private void exportFile(String directory, String exportResource) throws InterruptedException {
        File file = new File(exportResource);
        String destinationName = ""; //$NON-NLS-1$
        if (directory != null && !"".equals(directory)) { //$NON-NLS-1$
            destinationName = directory + PATH_SEPARATOR + destinationName;
        }
        File desFile = new File(this.destinationPath + PATH_SEPARATOR + destinationName);
        if (!desFile.exists()) {
            desFile.mkdirs();
        }

        monitor.subTask(exportResource);
        destinationName = this.destinationPath + PATH_SEPARATOR + destinationName + file.getName();
        File targetFile = new File(destinationName);
        if (targetFile.exists()) {
            if (!targetFile.canWrite()) {
                monitor.worked(1);
                return;
            }
        }
        try {
            exporter.write(exportResource, targetFile.getAbsolutePath());
        } catch (Exception e) {
            ExceptionOperation.operate(e);
        }

        monitor.worked(1);
        ModalContext.checkCanceled(monitor);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "countSelectedResources".
     * 
     * @return
     * @throws CoreException
     */
    private int countSelectedResources() throws CoreException {
        int result = 0;
        for (ExportFileResource fileList : zExportResList) {
            result += fileList.getFilesCount();
        }
        return result;
    }

}
